#!/usr/bin/perl -w

use DBI;
 
# Connect to database (configure dbname, hostname, port, username, and password).
my $db = DBI->connect("dbi:mysql:slsensor:localhost", "user", "password");

# Read data from POST request.
my $data;
read STDIN, $data, $ENV{'CONTENT_LENGTH'};
$data =~ s/\+/ /g;
$data =~ s/%([0-9a-f]{2})/pack("c",hex($1))/gie;

# Split records and insert them into the database.
foreach my $line (split /\n/, $data) {
  $line =~ s/\r?\n//;
  $line =~ s/"/\\"/g;
  $line =~ s/\\/\\\\/g;
  $line =~ s/'/\\'/g;
  my (undef, $time, $region, $x, $y, $z, $agent) = split /\t/, $line;
  my $q = $db->prepare("INSERT INTO sensordata VALUES ($time, '$region', $x, $y, $z, '$agent')");
  $q->execute();
}
